package oss

import (
	"app/pkg/config"
	"fmt"

	"github.com/aliyun/aliyun-oss-go-sdk/oss"
)

type AliOss struct{}

var aliOssClient *oss.Client

func ossClient() (client *oss.Client, err error) {
	if aliOssClient != nil {
		return aliOssClient, nil
	}
	client, err = oss.New(config.Config.Credential.Ali.OssEndpoint, config.Config.Credential.Ali.AccessKeyID, config.Config.Credential.Ali.AccessKeySecret)
	if err != nil {
		return
	}
	aliOssClient = client
	return client, nil
}

func DefaultBucket() (bucket *oss.Bucket, err error) {
	client, err := ossClient()
	if err != nil {
		return
	}
	return client.Bucket(config.Config.Credential.Ali.Bucket)
}

func NewAliOss() *AliOss {
	return &AliOss{}
}

func (o *AliOss) PreviewFileUrl(path string) string {
	val := fmt.Sprintf("%s/%s", config.Config.Credential.Ali.FinalHost, path)
	return val
}

func (o *AliOss) PreviewUrl(path string, width, height int) string {
	val := fmt.Sprintf("%s/%s", config.Config.Credential.Ali.FinalHost, path)
	if width > 0 || height > 0 {
		val = fmt.Sprintf("%s?x-oss-process=image/resize,m_fill", val)
		if width > 0 {
			val = fmt.Sprintf("%s,w_%d", val, width)
		}
		if height > 0 {
			val = fmt.Sprintf("%s,h_%d", val, height)
		}
	}
	return val
}
